/* eslint-disable */
import instance from '../../axios'
import store from '../../store'
import * as types from '../../store/mutation-types.js'

export default {
  // ******************* 登录、注册 *******************//
  /**
   * 检查当前是否处于登录状态
   * @param {[String]} token: 根据token验证是否登录，否则根据是否存在token判断
   */
  isLoggedIn(token) {
    if (token) {
      return instance.get('/isLoggedIn')
        .then(response => {
          store.commit(types.IS_LOGGED_IN, true);
          store.commit('USERINFO', {
            username: response.data.data.email
          });
          return response;
        })
        .catch(err => {
          store.commit(types.IS_LOGGED_IN, false);
          store.commit('USERINFO', {
            username: '未登录'
          });
          it.core.token(undefined); // 验证不通过就清除token
          return err;
        });
    } else {
      return it.exist(it.core.token());
    }
  },
  /**
   * 登录
   * @param options 登录相关参数
   */
  login({ email, password }) {
    // Clear stored token firstly.
    // it.core.token(undefined); // TODO:

    // let args = _.pick(options, ['email', 'password']);
    // args.deviceId = it.mobile.getDeviceUUID();
    return instance.post('/login', { email, password })
      .then(function(response) {
        // Store token if login successfully
        storeToken(response);
        store.commit(types.IS_LOGGED_IN, true);
        store.commit('USERINFO', {
          username: response.data.email
        });
        return response;
      });
  },
  /**
   * 登出
   */
  logout() {
    return instance.get('/logout')
      .then(function(response) {
        clean();
        store.commit(types.IS_LOGGED_IN, false);
        store.commit('USERINFO', {
          username: '未登录'
        });
        return true;
      })
      .catch(function() {
        clean();
        store.commit(types.IS_LOGGED_IN, false);
        store.commit('USERINFO', {
          username: '未登录'
        });
        return false;
      });

    function clean() {
      // Directly clear token
      it.core.token(undefined);
    }
  },
  /**
   * 注册普通用户
   * @param options 注册相关参数
   */
  register({email, password, mobile, username}) {
    // args.deviceId = it.mobile.getDeviceUUID();
    return instance.post('register', {email, password, mobile, username})
      .then(function(response) {
        // Store token if register successfully
        storeToken(response);
        return response;
      })
      .catch(rej => {
        console.error(rej);
      });
  }
}


function storeToken(response) {
  // Store token if login or register successfully
  let token = response.data && response.data.token || undefined;
  if (it.exist(token)) {
    it.core.token(token);
  }
  return response;
}
